/*
package com.bifrost.service.impl;

import OrderItemStatus;
import OrderItemType;
import OrderStatus;
import OrderType;
import com.bifrost.entity.*;
import OrderBaseInfo;
import OrderModel;
import OrderResult;
import ResultModel;
import ReturnRequest;
import OrderItemRepository;
import OrderRepository;
import com.bifrost.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

*/
/**
 * @author rangf
 * @date 2017/11/22
 *//*

@Service
public class RefundServiceImpl implements RefundService {

    @Autowired
    OrderRepository orderRepository;
    @Autowired
    OrderService orderService;
    @Autowired
    ProductSkuService productSkuService;
    @Autowired
    ProductSkuService skuService;
    @Autowired
    StoreService storeService;
    @Autowired
    OrderItemRepository orderItemRepository;
    @Autowired
    CustomerService customerService;
    @Autowired
    InventoryService inventoryService;
    @Autowired
    OrderStatusHistoryService statusHistoryService;

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyMMddHH");

    */
/**
     * 申请退货:保存订单项
     *
     * @param order order
     * @param item  item
     * @return 订单
     *//*

    @Override
    public Order addOrderItem(Order order, OrderItem item) {
        OrderItem itemRefund = new OrderItem();
        //保存退货单(项)
        ProductSku sku = skuService.getSkuById(item.getSkuId());
        itemRefund.setSkuId(item.getSkuId());
        itemRefund.setSkuName(item.getSkuName());
        itemRefund.setSkuPrice(item.getSkuPrice());
        itemRefund.setRetailPrice(sku.getRetailPrice());
        itemRefund.setSkuQuantity(item.getSkuQuantity());
        itemRefund.setOrderItemType(item.getOrderItemType());
        itemRefund.setCategoryId(sku.getCategory().getCategoryId());
        itemRefund.setProductId(sku.getProduct().getProductId());
        itemRefund.setDiscountShare(item.getDiscountShare());
        itemRefund.setShipShare(item.getDiscountShare());
        itemRefund.setOrder(order);
        //如果有服务
        if (Boolean.TRUE.equals(item.getHasService())) {
            itemRefund.setHasService(Boolean.TRUE);
            List<OrderItemService> services = item.getOrderItemServices();
            itemRefund.setOrderItemServices(new ArrayList<>());
            if (services != null && !services.isEmpty()) {
                services.forEach(service -> {
                    OrderItemService ois = new OrderItemService();
                    ois.setCurrencyCode(service.getCurrencyCode());
                    ois.setMerchantStore(service.getMerchantStore());
                    ois.setMerchantStoreName(service.getMerchantStoreName());
                    ois.setOrderItem(itemRefund);
                    ois.setProductService(service.getProductService());
                    ois.setServiceName(service.getServiceName());
                    ois.setServicePrice(ois.getServicePrice());
                    itemRefund.getOrderItemServices().add(ois);
                });
            }
        }
        //类型为礼品
        if (OrderItemType.GIFTWRAP.equalsIgnoreCase(item.getOrderItemType())) {
            itemRefund.setHasGift(Boolean.TRUE);
            itemRefund.setGiftwrapOrderItems(new ArrayList<>());
            List<GiftwrapOrderItem> giftWraps = item.getGiftwrapOrderItems();
            giftWraps.forEach(gidb -> {
                GiftwrapOrderItem gi = new GiftwrapOrderItem();
                gi.setOrderItem(itemRefund);
                gi.setGiftName(gidb.getGiftName());
                gi.setProductSku(sku);
                gi.setQuantity(gidb.getQuantity());
                itemRefund.getGiftwrapOrderItems().add(gi);
            });
            itemRefund.setGiftwrapOrderItems(item.getGiftwrapOrderItems());
        }
        //类型为绑定 保存入库
        if (OrderItemType.BUNDLE.equalsIgnoreCase(item.getOrderItemType())) {
            List<OrderBundleItem> obs = item.getOrderBundleItems();
            itemRefund.setOrderBundleItems(new ArrayList<>());
            if (obs != null && !obs.isEmpty()) {
                obs.forEach(ob -> {
                    OrderBundleItem refundOb = new OrderBundleItem();
                    refundOb.setItemQuantity(ob.getItemQuantity());
                    refundOb.setOrder(order);
                    refundOb.setOrderItem(itemRefund);
                    refundOb.setProduct(ob.getProduct());
                    refundOb.setProductSku(ob.getProductSku());
                    refundOb.setRetailPrice(ob.getRetailPrice());
                    refundOb.setSalePrice(ob.getSalePrice());
                    item.getOrderBundleItems().add(refundOb);
                });
            }

        }
        order.getOrderItems().add(itemRefund);
        return order;
    }

    */
/**
     * 申请退货:单品退货
     *
     * @param customer customer
     * @param order    order
     * @param item     item
     * @param request  request
     * @return 订单
     *//*

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Order applyItem(Customer customer, Order order, OrderItem item, ReturnRequest request) {
        //保存订单
        Order refundOrder = new Order();
        refundOrder.setRelatedOrderNumber(order.getOrderNumber());
        refundOrder.setCustomer(customer);
        refundOrder.setOrderType(OrderType.REFUND);
        refundOrder.setOrderStatus(OrderStatus.PURCHASED);
        refundOrder.setMerchantStore(order.getMerchantStore());
        refundOrder.setOrderTotal(item.getSkuPrice().subtract(item.getDiscountShare()));
        refundOrder.setOrderItems(new ArrayList<OrderItem>());
        refundOrder.setCustomerMessage(request.getDesc());
        refundOrder = addOrderItem(refundOrder, item);
        Order dbOrder = orderService.save(refundOrder);
        //更改原订单项状态为：退货中
        item.setStatus(OrderItemStatus.REFUNDING);
        orderItemRepository.save(item);
        //保存订单项
        dbOrder.setOrderNumber(String.format("%s%d%d", LocalDateTime.now().format(FORMATTER), order.getMerchantStore().getMerchantId(), dbOrder.getOrderId()));
        return dbOrder;
    }

    */
/**
     * 申请退货:整单退货
     *
     * @param customer customer
     * @param request  request
     * @return 订单
     *//*

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Order applyOrder(Customer customer, Order order, ReturnRequest request) {
        //保存订单
        Order refundOrder = new Order();
        //BeanUtils.copyProperties(order,refundOrder);
        refundOrder.setOrderType(OrderType.REFUND);
        refundOrder.setOrderStatus(OrderStatus.PURCHASED);
        refundOrder.setRelatedOrderNumber(order.getOrderNumber());
        refundOrder.setCustomer(customer);
        refundOrder.setMerchantStore(order.getMerchantStore());
        refundOrder.setOrderTotal(order.getOrderTotal());
        refundOrder.setOrderItems(new ArrayList<OrderItem>());
        refundOrder.setCustomerMessage(request.getDesc());
        refundOrder.setNeedService(order.isNeedService());
        refundOrder.setServiceShop(order.getServiceShop());
        List<OrderItem> items = order.getOrderItems();
        if (items == null || items.isEmpty()) {
            return null;
        }
        //保存订单项
        for (OrderItem item : items) {
            //更改原订单项状态为：退货中
            item.setStatus(OrderItemStatus.REFUNDING);
            orderItemRepository.save(item);
            refundOrder = addOrderItem(refundOrder, item);
        }
        Order dbOrder = orderService.save(refundOrder);
        order.setLocked(Boolean.TRUE);
        orderService.save(order);
        dbOrder.setOrderNumber(String.format("%s%d%d", LocalDateTime.now().format(FORMATTER), order.getMerchantStore().getMerchantId(), dbOrder.getOrderId()));
        statusHistoryService.writeHistory(dbOrder, "提交成功");
        return dbOrder;
    }

    */
/**
     * 获取所有退货订单
     *
     * @param page     page
     * @param pageSize pageSize
     * @param customer customer
     * @param status   status
     * @return 订单
     *//*

    @Override
    public List<OrderResult> getOrders(Integer page, Integer pageSize, Customer customer, String status) {
        List<OrderResult> orders = new ArrayList<>();
        Pageable pageable = new PageRequest(page - 1, pageSize, new Sort(Sort.Direction.DESC, "updatedTimestamp"));
        Specification<Order> query = new Specification<Order>() {
            @Override
            public Predicate toPredicate(Root<Order> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (!StringUtils.isEmpty(status)) {
                    predicates.add(cb.equal(root.get("orderStatus"), status));
                }
                predicates.add(cb.equal(root.get("customer"), customer));
                predicates.add(cb.equal(root.get("orderType"), OrderType.REFUND));
                Predicate[] p = new Predicate[predicates.size()];
                return cb.and(predicates.toArray(p));
            }
        };
        Page<Order> data = orderRepository.findAll(query, pageable);
        if (!data.hasContent()) {
            return null;
        }
        List<Order> list = data.getContent();
        if (list == null || list.isEmpty()) {
            return null;
        }
        for (Order order : list) {
            OrderResult orderResult = orderService.orderOverview(order);
           */
/* OrderResult orderResult = new OrderResult();
            orderResult.setOrderId(order.getOrderId());
            List<OrderItem> items = order.getOrderItems();
            if(items == null || items.isEmpty()){
                continue;
            }
            OrderItem itemFirst = items.get(0);
            orderResult.setSkuName(itemFirst.getSkuName());
            ProductSku sku = productSkuService.getSkuById(itemFirst.getSkuId());
            Media media = productSkuService.getSkuDefaultMedia(sku);
            orderResult.setUrl(media == null ? null : media.getUrl());
            orderResult.setTotleFee(order.getOrderTotal());
            orderResult.setOrderNumber(order.getOrderNumber());
            orderResult.setStatus(order.getOrderStatus());
            orderResult.setOrderStatus("");
            Long quantity = orderRepository.countOrderItem(order.getOrderId());
            orderResult.setQuantity(quantity == null ? 1L : quantity);*//*

            if (orderResult != null)
                orders.add(orderResult);
        }
        return orders;
    }

    */
/**
     * 获取退货单明细
     *
     * @param orderId orderId
     * @return 订单
     *//*

    @Override
    public ResultModel getOrder(Long orderId) {
        Order order = orderService.findOrderById(orderId);
        OrderModel model = orderService.convertToOrderModel(order);
        OrderBaseInfo info = orderService.convertToOrderBaseInfo(order);
        //是否可取消
        boolean canCancel = false;
        //是否可寄送：
        boolean canShip = false;
        //申请退货，后台还未审核
        if (OrderStatus.PURCHASED.equalsIgnoreCase(order.getOrderStatus())) {
            canCancel = true;
        } else if (OrderStatus.CONFIRMED.equalsIgnoreCase(order.getOrderStatus())) {
            //快递退单
            if (!Boolean.TRUE.equals(order.isNeedService())) {
                canCancel = true;
                canShip = true;
            }
        } else {
        }
        return ResultModel.ok()
                .put("canCancel", canCancel)
                .put("canship", canShip)
                .put("info", info)
                .put("order", model);
    }

    */
/**
     * 确认退货、邮寄商品
     *
     * @param customer   customer
     * @param orderId    orderId
     * @param shipNumber shipNumber
     * @return 订单
     *//*

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean confirmShip(Customer customer, Long orderId, String shipNumber) {
        Boolean flag = Boolean.FALSE;
        Order order = orderService.findOrderByIdAndCustomer(orderId, customer);
        if (order != null && OrderType.REFUND.equals(order.getOrderType()) && OrderStatus.CONFIRMED.equals(order.getOrderStatus())) {
            order.setShippingModuleCode(shipNumber);
            //确认寄出商品
            order.setOrderStatus(OrderStatus.SHIPPED);
            //回滚积分
           */
/* Integer orderPoints = orderService.countBonusPoints(order);
            BigInteger customerPoints =  customer.getBonusPoints();
            if(customerPoints != null && customerPoints.compareTo(BigInteger.valueOf(orderPoints)) >= 0){
                customer.setBonusPoints(customerPoints.subtract(BigInteger.valueOf(orderPoints)));
            }
            customerService.saveCustomer(customer);*//*

            //回滚库存
            */
/*Map<ProductSku, Integer> map = inventoryService.buildSkuInventoryMap(order);
            inventoryService.incrementInventory(map);*//*

            flag = Boolean.TRUE;
        }
        return flag;
    }

    */
/**
     * 取消退单
     *
     * @param customer customer
     * @param orderId  orderId
     * @return
     *//*

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Boolean cancel(Customer customer, Long orderId) {
        Boolean flag = Boolean.FALSE;
        Order order = orderService.findOrderByIdAndCustomer(orderId, customer);
        if (order != null && OrderType.REFUND.equalsIgnoreCase(order.getOrderType())) {
            if (OrderStatus.PURCHASED.equals(order.getOrderStatus()) || OrderStatus.CONFIRMED.equals(order.getOrderStatus())) {
                order.setOrderStatus(OrderStatus.CANCELED);
                orderRepository.save(order);
                flag = Boolean.TRUE;
            }
        }
        return flag;
    }
}
*/
